package com.liujie.app.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liujie.app.dao.AppInfoDao;
import com.liujie.app.dao.AppVersionDao;
import com.liujie.app.dto.AppInfoDto;
import com.liujie.app.entity.AppInfo;
import com.liujie.app.entity.AppVersion;
import com.liujie.app.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

@Service
public class AppInfoService {

    @Autowired
    AppInfoDao appInfoDao;
    @Autowired
    AppVersionDao appVersionDao;

    public PageInfo<AppInfo> getPage(AppInfoDto appInfoDto, Integer pageNum) {
        PageHelper.startPage(pageNum,5,"id desc");
        AppInfo appInfo=new AppInfo();
        BeanUtils.copyProperties(appInfoDto,appInfo);
        List<AppInfo> pageInfo=appInfoDao.queryAllByLimit(appInfo);
        return new PageInfo(pageInfo);
    }

    public Result getInsertOrUpdate(AppInfo appInfo) {
        if (appInfo.getId()==null){
            appInfoDao.insert(appInfo);
        }else {
            appInfoDao.update(appInfo);
        }
        return Result.success();
    }

    public int getApkName(String apkName) {
        int i = appInfoDao.selApkName(apkName);
        return i;
    }

    public AppInfo getAppId(Integer id) {
        AppInfo appInfo = appInfoDao.queryById(Long.valueOf(id));
        return appInfo;
    }

    public int getDelAppInfo(Integer id, HttpServletRequest request) {
        AppInfo appInfo = appInfoDao.queryById(Long.valueOf(id));
        String realPath = request.getServletContext().getRealPath("");
        new File(realPath+appInfo.getLogopicpath()).delete();
        AppVersion appVersion=new AppVersion();
        appVersion.setAppid(Long.valueOf(id));
        List<AppVersion> appVersions = appVersionDao.queryAllByLimit(appVersion);
        for (AppVersion version : appVersions) {
            new File(realPath+version.getDownloadlink()).delete();
        }
        appVersionDao.deleteById(Long.valueOf(id));
        int i = appInfoDao.deleteById(Long.valueOf(id));
        return i;
    }

    public int getUpdateStatus(Integer id, Integer status) {
        AppInfo appInfo=new AppInfo();
        appInfo.setId(Long.valueOf(id));
        appInfo.setStatus(Long.valueOf(status));
        int update = appInfoDao.update(appInfo);
        return update;
    }
}
